<?php
namespace jy_pinggou;
defined('BY_JYA') or exit('error');
/*
	订单
*/
class order extends \plugin{
	// $noping 表示不能参与的拼团
	public function openteam($pinggoods,$mid=0,$noping=false){
		$mid=$mid?:$_SESSION['uid'];
		//$teamid=$this->getteamid($pinggoods,0);
		//if($teamid){
		//	return $teamid;
		//}
		$timeid=$this->model('model')->get_timeid($pinggoods['timeids']);
		if($timeid!='fail'){
			$insertdata=array(
				'uniacid'=>$_SESSION['uniacid'],
				'goodsid'=>$pinggoods['goodsid'],
				'mid'=>$mid,
				'timeid'=>$timeid,
				'dayid'=>date('Y-m-d',TIMESTAMP),
				'plugin_name'=>'jy_pinggou',
				'noping'=>$noping?1:0,
				'status'=>0,
				'createtime'=>TIMESTAMP
			);
			pdo_insert('jy_weishop_groups_team',$insertdata);
			$teamid=pdo_insertid();
		}
		return $teamid;
	}
	/*
		获取timeid
	*/
	public function getteamid($pinggoods,$status=0,$canzhong=false){
		$timeid=$this->model('model')->get_timeid($pinggoods['timeids']);
		$params=array(
				'uniacid'=>$_SESSION['uniacid'],
				'goodsid'=>$pinggoods['goodsid'],
				'status'=>$status,
				'timeid'=>$timeid,
				'dayid'=>date('Y-m-d',TIMESTAMP),
				'plugin_name'=>'jy_pinggou',
				'noping'=>0,
		);
		if($status!=10){
			$params['status']=$status?:0;
		}
		$allteams=pdo_getall('jy_weishop_groups_team',$params,'id');
		$count=count($allteams);
		if(!$count){
			return false;
		}
		$teamid=$allteams[0]['id'];
		if($count>1 && !$canzhong){
			//不能中的，获取最新的
			$countkey=$count-1;
			$teamid=$allteams[$countkey]['id'];
		}
		//不能中时
		if(!$canzhong && $teamid){
			$nocannum=pdo_count('jy_pinggou_log',array('status'=>1,'type'=>0,'canzhong'=>0,'uniacid'=>$_SESSION['uniacid'],'teamid'=>$teamid),'id');
			$maxnum=$pinggoods['teamnum']-$pinggoods['lastnum'];
			//file_put_contents(ROOT_D.'/1.txt',$pinggoods['id'].'~'.$nocannum.'~'.$maxnum."\n",FILE_APPEND);
			if($nocannum && $pinggoods['teamnum'] && $maxnum && $nocannum>=$maxnum){
				return false;
			}
		}
		return $teamid;
	}
	/*
		自动拼团
	*/
	public function create($pinggoods,$yuyue=array()){
		$mid=$yuyue['mid']?:$_SESSION['uid'];
		$timeid=$this->model('model')->get_timeid($pinggoods['timeids']);
		if($timeid=='fail'){
			return false;
		}
		$isping=$this->model('model')->che_isping($pinggoods['id'],$mid,$timeid);
		if($isping){
			return false;
		}
		$item=$this->model('member')->getdetail($mid);
		if($pinggoods['price']>$item['freeze']){
					$params=array(
						'pingid'=>$pinggoods['id'],
						'msg'=>'参与拼团失败，冻结的倍财金不足！',
						'status'=>0,
						'timeid'=>$timeid,
						'dayid'=>date('Y-m-d',TIMESTAMP),
						'mid'=>$mid,
					);
					$this->model('model')->set_log($params,0);
					return false;
		}
		//看还可以中不？
		$canzhong=$yuyue['canzhong'];
		$teamid=$this->getteamid($pinggoods,0,$canzhong);
		if(!$teamid){
			$teamid=$this->openteam($pinggoods,$mid);
		}
		$goods=pdo_get('jy_weishop_goods',array('id'=>$pinggoods['goodsid'],'uniacid'=>$_SESSION['uniacid']),array('id','title','type'));
		$goods['total']=1;
		$goods['goodsid']=$pinggoods['goodsid'];
		$goods['price']=$pinggoods['price'];
		$list=array();
		$list[]=$goods;
		$sendtype=$goods['type']==0?1:3;
		$new_order=array(
			'mid'=>$mid?:$_SESSION['uid'],
			'goodsprice'=>$pinggoods['price'],
			'remark'=>'预约自动拼团',
			'goods'=>$list,
			'merchid'=>$goods['merchid'],
			'sendtype'=>$sendtype,
		);
		$new_order['price']=$pinggoods['price']>0?$pinggoods['price']:0;
		//拼单部分
		$new_order['addressid']=$yuyue['addressid'];
		$new_order['teamid']=$teamid;
		$new_order['is_team']=1;
		$new_order['plugin_name']='jy_pinggou';
		$order_id=$this->ordercreate($new_order,'','',true);
		/*$params=array(
			'id'=>$order_id,
			'title'=>'自动拼单',
			'fee'=>$new_order['price'],
			//'pay_type'=>'wechat',//可选，此项作用为指定支付方式
			'no_type'=>array('hdfk'),//可选，此项作用为指定不允许使用哪种支付方式
			'back_url'=>'jy_pinggou/order.create/payresult/',//必填，指定异步支付结果通知地址，采用系统标准URL书写格式
			'success_url'=>'jy_pinggou/myteam/',
			'error_url'=>'jy_pinggou/myteam/',
		);
		$payid=cfc('pay')->create_pay_order($params);
		pdo_update('jy_weishop_order',array('pay_id'=>$payid),array('id'=>$order_id));*/
		$this->model('member')->recharge($new_order['mid'],$new_order['price'],4,'拼团消费倍财金');
		$params=array(
			'paytype'=>'',
			'transid'=>'',
			'status'=>10,
		);
		$this->order_pay($order_id,$params,'',true);
		$params=array(
			'pingid'=>$pinggoods['id'],
			'msg'=>'参与拼团成功！',
			'status'=>1,
			'timeid'=>$timeid,
			'dayid'=>date('Y-m-d',TIMESTAMP),
			'mid'=>$new_order['mid'],
			'teamid'=>$new_order['teamid'],
			'canzhong'=>$canzhong,
		);
		$this->model('model')->set_log($params,0);
		$params['orderid']=$order_id;
		$this->model('renwu')->canyu($params,$pinggoods);
		$this->upstarttime($new_order['mid'],$pinggoods);
		//拼单部分
		$num=pdo_count('jy_weishop_order',array('uniacid'=>$_SESSION['uniacid'],'status'=>10,'plugin_name'=>'jy_pinggou','teamid'=>$new_order['teamid']),'id');
		$goods=$this->model('model')->up_price($goods,$return['pluginset']);
		if($goods['teamnum']<=$num){
			$this->model('model')->order_success($new_order['teamid']);
		}else{
			$new_order['goodstitle']=$goods['title'];
			$new_order['orderprice']=$new_order['price'];
			$new_order['createtime']=TIMESTAMP;
			//model('jy_weishop/notice')->notice_groupfinish_dingcan($new_order);
		}
		return $order_id;
	}
	public function ordercreate($params,$uid='',$url='',$notpl=false){
		$this->order=$params;
		$this->order['createtime']=TIMESTAMP;
		$uid=$uid?$uid:$_SESSION['uid'];
		$order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'ordersn'=>$params['ordersn']?:get_ordersn('jy_weishop_order','ordersn'),
			'mid'=>$params['mid']?:$uid,
			'price'=>$params['price'],
			'ding_price'=>$params['ding_price']?:0,
			'outnum_fee'=>$params['outnum_fee'],
			'goodsprice'=>$params['goodsprice'],
			'dispatchprice'=>$params['dispatchprice'],
			'level_de_price'=>$params['level_de_price'],
			'luck_de_price'=>$params['luck_de_price'],
			'buyxiu_de_price'=>$params['buyxiu_de_price'],
			'enough_de_price'=>$params['enough_de_price'],
			'coupon_de_price'=>$params['coupon_de_price'],
			'deductcredit'=>$params['deduct_credit'],
			'delcredit1'=>$params['delcredit1'],
			'deductcredit2'=>$params['deduct_credit2'],
			'couponid'=>$params['couponid'],
			'remark'=>$params['remark'],
			'sendtype'=>$params['sendtype'],
			'addressid'=>$params['addressid'],
			'address'=>$params['address']?ijson_encode($params['address']):'',
			'storeid'=>$params['storeid'],
			'merchid'=>$params['merchid']?:$params['goods']['0']['merchid'],
			'plugin_name'=>$params['plugin_name']?:$_SESSION['current_plugin'],
			'tableid'=>intval($params['tableid'])?:$_SESSION['table_id'],
			'area_code'=>$area_code,
			'isdish'=>intval($params['isdish']),
			'diyformdata'=>$params['diyfields'],
			'createtime'=>$params['createtime']?:TIMESTAMP,
			'teamid'=>intval($params['teamid']),
			'is_team'=>intval($params['is_team']),
			'send_status'=>intval($params['send_status']),
			'out_upfee'=>$params['out_upfee'],
			'api_id'=>$params['api_id']?:$params['goods']['0']['api_id'],
			'api_pluginname'=>$params['api_pluginname']?:$params['goods']['0']['api_pluginname'],
		);
		/*
			核销
		*/
		$num=0;
		$verifynum=0;
		foreach($params['goods'] as &$gv){
			$goodsinfo=pdo_get('jy_weishop_goods',array('id'=>$gv['goodsid']),array('merchid','totalcnf','api_id','api_pluginname'));
			$gv['merchid']=$goodsinfo['merchid'];
			$gv['api_id']=$goodsinfo['api_id'];
			$gv['api_pluginname']=$goodsinfo['api_pluginname'];
			if($goodsinfo['totalcnf']==0){
					//拍下减库存
				if($gv['optionid']){
					pdo_update('jy_weishop_goods_option',array('stock -='=>$gv['total']),array('id'=>$gv['optionid']));
				}else{
					pdo_update('jy_weishop_goods',array('total -='=>intval($gv['total'])),array('id'=>$gv['goodsid']));
				}
			}
			//判断订单核销分量
			$num +=1;
			if($gv['isverify']==1){
				$verifynum +=1;
			}
		}
		if($verifynum==$num && $verifynum>0){
			$order['isverify']=2;
		}elseif($verifynum<$num && $verifynum>0){
			$order['isverify']=1;
		}else{
			$order['isverify']=0;
		}
		//来源追加订单
		if($params['oldorderid']){
			$uporder=$order;
			unset($uporder['mid'],$uporder['uniacid'],$uporder['ordersn'],$uporder['createtime'],$uporder['storeid']);
			$order_id=$params['oldorderid'];
			pdo_update('jy_weishop_order',$uporder,array('id'=>$order_id));
		}else{
			pdo_insert('jy_weishop_order',$order);
			$order_id=pdo_insertid();
		}
		$this->order['id']=$order_id;
		$this->order['ordersn']=$order['ordersn'];
		//店内取
		if(!$params['oldorderid'] && ($params['sendtype']==2 || $params['sendtype']==3 || $params['isdish']==1 || $params['make_type']==1 || $params['is_peisong']==1)){
			if($uid){
				$mobile=pdo_getcolumn('core_members',array('id'=>$uid),'mobile');	
				$nickname=pdo_getcolumn('core_members',array('id'=>$uid),'nickname');	
			}else{
				$mobile=$params['mobile']?$params['mobile']:'无';
				$nickname=$params['username']?$params['username']:'店面客户';
			}
			$address=pdo_get('core_address',array('id'=>$params['addressid']),array('pcd','address','mobile','name'));
			$address['pcd']=json_decode($address['pcd'],true);
			$addressinfo=$address['pcd']['province'].' '.$address['pcd']['city'].' '.$address['pcd']['district'].' '.$address['pcd']['street'].''.$address['address'];
			$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$selfcount=pdo_count('jy_weishop_order_self',array('uniacid'=>$_SESSION['uniacid'],'createtime >'=>$daytime),'id');
			$daysnum=date('Ymd',time());
			$selfnumber='NO'.$daysnum.sprintf("%04d", $selfcount+1);
			$self=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$params['mid']?:$uid,
				'storeid'=>$params['storeid'],
				'orderid'=>$order_id,
				'table_id'=>intval($params['tableid'])?:$_SESSION['table_id'],
				'username'=>$address['name']?:$nickname,
				'mobile'=>$address['mobile']?:$mobile,
				'address'=>$addressinfo,
				'number'=>$selfnumber,
				'status'=>0,
				'type'=>intval($params['self_type']),
				'selftime'=>$params['selftime']?strtotime($params['selftime']):'',
				'out_time'=>trim($params['out_time']),
				'createtime'=>time()
			);
			pdo_insert('jy_weishop_order_self',$self);
		}
		//整理订单商品
		foreach($params['goods'] as $item){
			$new_order_goods=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$params['mid'],
				'orderid'=>$order_id,
				'goodsid'=>$item['goodsid'],
				'optionid'=>$item['optionid'],
				'price'=>$item['price'],
				'total'=>$item['total'],
				'merchid'=>$item['merchid'],
				'plugin_name'=>$this->session('fromplugin_name'),
				'frompid'=>$this->session('frompid'),
				'fee_desc'=>ijson_encode($fee_desc),
				'api_id'=>$item['api_id'],
				'api_pluginname'=>$item['api_pluginname'],
				'active'=>$item['active']?ijson_encode($item['active']):'',
				'createtime'=>TIMESTAMP,
			);
			if($new_order_goods['optionid']){
					$specs=pdo_get('jy_weishop_goods_option',array('id'=>$item['optionid']),'specs');
					$specstitle=explode("_",$specs['specs']);
					foreach($specstitle as &$spec){
						$spec=pdo_getcolumn('jy_weishop_goods_spec_item',array('id'=>$spec),'title');
					}
					$new_order_goods['optiondata']=implode(" ",$specstitle);
			}
			$new_order_goods['total_price']=$new_order_goods['price']*$new_order_goods['total'];
			pdo_insert('jy_weishop_order_goods',$new_order_goods);
		}
		return $order_id;
	}
	//支付
	public function order_pay($order_id,$params,$url='',$notpl=false){
		$this->get_order($order_id);
		if(!$this->order || $this->order['ispay']){
			exi('订单不存在或者已支付！','error');
		}
		$update=array(
				'status'=>$params['status']?:1,
				'paytype'=>$params['paytype'],
				'transid'=>$params['transid'],
		);
		if($params['paytype']=='hdfk'){
			$update['ispay']=0;
		}else{
			$update['ispay']=1;
			$update['paytime']=TIMESTAMP;
		}
		foreach($update as $key=>$value){
			$this->order[$key]=$value;
		}
		pdo_update('jy_weishop_order',$update,array('id'=>$order_id));
		//更新单商品支付状态
		pdo_update('jy_weishop_order_goods',array('status'=>1,'ispay'=>$update['ispay']),array('orderid'=>$order_id));
		$noticemids=array();
		foreach($this->order['goods'] as $item){
			$goodsinfo=pdo_get('jy_weishop_goods',array('id'=>$item['goodsid']),array('noticemid','totalcnf','noticetype'));
			if($goodsinfo['totalcnf']==1){
				//付款减库存
				if($item['optionid']){
					pdo_update('jy_weishop_goods_option',array('stock -='=>$item['total']),array('id'=>$item['optionid']));
				}else{
					pdo_update('jy_weishop_goods',array('total -='=>$item['total']),array('id'=>$item['goodsid']));
				}
			}
			pdo_update('jy_weishop_goods',array('salerealnum +='=>1,'salenum +='=>$item['total']),array('id'=>$item['goodsid']));			
		}
		//会员等级变更
		//model('jy_weishop/member')->check_uplevel($this->order['mid'],1);
	}
	public function upstarttime($mid,$pinggoods){
		$mid=$mid?:$_SESSION['uid'];
		$pindays=pdo_get('jy_pinggou_pindays',array('mid'=>$mid,'pingid'=>$pinggoods['id'],'uniacid'=>$_SESSION['uniacid']));		
		if($pindays['starttime']){
			$pin_days=intval($pinggoods['pin_days'])?:7;
			$endtime=$pin_days*24*3600+$pindays['starttime'];
			if($endtime<TIMESTAMP){
				pdo_update('jy_pinggou_pindays',array('starttime'=>TIMESTAMP),array('mid'=>$mid,'pingid'=>$pinggoods['id'],'uniacid'=>$_SESSION['uniacid']));
			}
		}else{
			$insert=array(
				'mid'=>$mid,
				'pingid'=>$pinggoods['id'],
				'uniacid'=>$_SESSION['uniacid'],
				'starttime'=>TIMESTAMP,
				'createtime'=>TIMESTAMP,
			);
			pdo_insert('jy_pinggou_pindays',$insert);	
		}
		return false;
	}
	public function get_order($order_id,$merchid=0){
		if($this->order && $this->order['id']==$order_id){
			return $this->order;
		}
		$this->order=pdo_get('jy_weishop_order',array('id'=>$order_id,'uniacid'=>$_SESSION['uniacid']));
		if($merchid){
			$this->order['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id,'merchid'=>$merchid));
		}else{
			$this->order['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id));
		}
		foreach($this->order['goods'] as &$goods){
			$goods_data=pdo_get('jy_weishop_goods',array('id'=>$goods['goodsid']),array('title','image','type','isverify','goodssn','productsn'));
			$goods=array_merge($goods,$goods_data);
		}
		$this->order['express']=pdo_get('jy_weishop_order_express',array('orderid'=>$order_id));
		return $this->order;
	}
}